package io.alvin.ch02;

/**
 * Integer是不变对象，Syncronzied加锁每次都加在不同的Integer对象上，临界区代码控制有误。
 * Synchronized应该监控static可变对象instance，能够起到同步作用。
 *
 * Created by Alvin on 2017/7/7.
 */
public class BadLockOnInteger implements Runnable {

    public static Integer i = 0;

    static BadLockOnInteger instance = new BadLockOnInteger();

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        for (int j = 0; j < 1_000_000; j++) {
            //synchronized (i) {
            synchronized (instance) {
                i++;
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start(); t2.start();
        t1.join(); t2.join();
        System.out.println(i);
    }
}
